package com.shadow.baiqun.delegate.receive.goodsscan;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.delegate.common.ResultConverter;
import com.shadow.baiqun.delegate.receive.adapter.GoodsScanAdapter;
import com.shadow.baiqun.delegate.receive.adapter.ItemName;
import com.shadow.baiqun.delegate.receive.partcheck.PartCheckDelegate;
import com.shadow.baiqun.event.RefreshPreOrderListEvent;
import com.shadow.baiqun.view.TableHeadView;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.core.util.toast.ToastUtils;
import com.shadow.ui.recycler.MultipleItemEntity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author zy
 * on 2018/5/30
 * 货物归位
 */
public class GoodsScanDelegate extends RxShadowDelegate {
    private static final String ORDER_ID = "orderId";

    public static GoodsScanDelegate create(int orderId) {
        final GoodsScanDelegate delegate = new GoodsScanDelegate();
        final Bundle bundle = new Bundle();
        bundle.putInt(ORDER_ID, orderId);
        delegate.setArguments(bundle);
        return delegate;
    }

    private static final int PAGE_SIZE = 50;
    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.lv_title)
    TableHeadView mHeadView;
    private GoodsScanAdapter mScanAdapter;
    private int mPreGoodsOrderId;
    private int mNextRequestPage = 1;
    //正在请求
    private boolean isRequesting = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mPreGoodsOrderId = bundle.getInt(ORDER_ID);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_goods_scan;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop();
                }
            });
            mToolbar.setTitle("货物归位");
        }
        List<String> list = new ArrayList<>();
        list.add(getContext().getResources().getString(R.string.part_n));
        list.add(getContext().getResources().getString(R.string.pre_total_count));
        list.add(getContext().getResources().getString(R.string.scan_count));
        list.add("操作");
        mHeadView.setHeaders(list);
        mScanAdapter = new GoodsScanAdapter(R.layout.item_goods_scan, null);
        mScanAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, mRecyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mScanAdapter);
        mScanAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
        if (mScanAdapter.getEmptyView() != null) {
            mScanAdapter.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refresh();
                }
            });
        }
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                if (entity != null) {
                    int id = entity.getField(ItemName.ITEM_PART_C_ID);
                    start(PartCheckDelegate.create(String.valueOf(id)));
                }
            }
        });
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);

    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        refresh();
    }

    private void requestData(final boolean isRefresh) {
        isRequesting = true;
        mDisposables.add(RxRestClient.builder()
                .url("WMS/backstage/collectgoods/getCollectGoodsPartesListForScan")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mScanAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        GoodsScanConverter converter = new GoodsScanConverter();
                        converter.setJsonData(response);
                        ArrayList<MultipleItemEntity> itemEntities = converter.convert();
                        setData(isRefresh, itemEntities);
                        isRequesting = false;
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mScanAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        isRequesting = false;
                    }
                })
                .params("pgid", mPreGoodsOrderId)
                .params("page", mNextRequestPage)
                .params("rows", PAGE_SIZE)
                .build()
                .unRestGet());
    }

    @OnClick(R2.id.tv_pause)
    public void onPauseComplete() {
        postCompleteState(2);
    }

    @OnClick(R2.id.tv_receive_goods)
    public void onReceiveGoods() {
        postCompleteState(1);
    }

    private void postCompleteState(final int type) {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/collectgoods/sureCollectGoods")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        String msg;
                        if (new ResultConverter().isSucceed(response)) {
                            if (type == 2) {
                                msg = "暂结成功";
                            } else {
                                msg = "收货成功";
                            }
                            ToastUtils.showToast(getContext(), msg);
                            EventBus.getDefault().post(new RefreshPreOrderListEvent());
                            pop();
                        } else {
                            if (type == 2) {
                                msg = "暂结失败";
                            } else {
                                msg = "收货失败";
                            }
                            ToastUtils.showToast(getContext(), msg);
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        ToastUtils.showToast(getContext(), msg);
                    }
                })
                .params("type", type)
                .params("pgid",mPreGoodsOrderId)
                .build()
                .unRestGet());
    }

    private void refresh() {
        if (!isRequesting) {
            mNextRequestPage = 1;
            isRequesting = true;
            mScanAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
            requestData(true);
        }
    }

    private void setData(boolean isRefresh, List<MultipleItemEntity> data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mScanAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mScanAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mScanAdapter.loadMoreEnd(isRefresh);
        } else {
            mScanAdapter.loadMoreComplete();
        }
    }

    private void loadMore() {
        requestData(false);
    }
}
